%%%%%%%%%%%%%%%%%%%%%%%%%
% ava.tex               %
% AVA User's Manual     %
% Uros Platise (c) 1999 %
%%%%%%%%%%%%%%%%%%%%%%%%%


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% General Environment Definitions

\documentclass[a4paper,twoside]{book}
\usepackage[dvips]{epsfig}
%\usepackage[]{rotating}

% The following option might be used with B5 paper configuration.
\raggedbottom

\newcommand{\fig}[3]
  {\begin{figure} \begin{center}
   \epsfig{file=#1} \caption{#2} \label{#3} 
   \end{center} \end{figure}}

\newcommand{\figHere}[3]
  {\begin{figure}[h] \begin{center}
   \epsfig{file=#1} \caption{#2} \label{#3} 
   \end{center} \end{figure}}

% AVR magic
\newcommand{\AVR}
  {{\bf \em AVR} }
  
% AVA magic
\newcommand{\AVA}
  {AVA }

% The way segment names are printed  
\newcommand{\seg}[1]
  {{\tt #1}}
  
% WWW Links
\newcommand{\wwwlink}[1]
  {\begin{quote}\tt #1 \end{quote}}
  
% Remarks
\newcommand{\remark}[1]
  {\emph{#1}}

% AVA Steps
\newcommand{\astep}[1]
  {\begin{quote}\tt #1 \end{quote}}
  
% AVA Inline Steps
\newcommand{\aistep}[1]
  {{\tt #1}}
  
% AVA Specials

% directory
\newcommand{\sdir}[1]
  {{\tt #1}}
  
\newcommand{\sfile}[1]
  {\emph{#1}}


% Theorems
\newtheorem{example}{Example}

  
% Notes
\newcommand{\note}[1]
  {\begin{description}\item[Note] #1 \end{description}}

% My Info
\title{{\bf AVA User's Manual} \\ {\tt version 0.2.5}}
\author{Uro\v s Plati\v se}
%\date{18. February 1999}
\date{12. March 1999}


\begin{document}
\maketitle

\tableofcontents


\chapter{Introduction}
 
  Even though small micro-controllers are getting stronger and 
  stronger every day there is still a lot of code to be written in 
  pure assembler. For example
  kernel itself, device drivers, fast interrupt routines,
  optimized mathematics functions, etc.
  
  \AVA (assembler and linker)
  was mainly designed for 8 and 16 bit micro-controllers
  but can be easily extended to 32 bit families also.
  In addition to standard assemblers for micro-controllers
  it features powerful segments and \emph{virtual} symbols.
  These two features improve modular programming and
  allow objects to be completely independed from each other.
  
  \AVA integrates two packages:
  \begin{enumerate}
    \item Assembler and
    \item Linker
  \end{enumerate}
  Depending on the command line parameters it executes either the
  first or the second one. Libraries are supported by the
  ordinary objects where each function can be declared in its own
  segment which is removed if not needed.
  
  \AVA User's Manual is divided into the following chapters:
  \begin{enumerate}
    \item Installation \\
      \emph{
        Gives references to downloading locations, 
        compiling and installation procedure.
      }          
    \item Running the \AVA \\
      \emph{
        This chapter describes input/output streams and command line options.
      }
    \item Assembler Language \\
      \emph{
        Explanation of Preprocessor, Symbols, Segments and other Keywords.
      }
    \item Programming in \AVA \\
      \emph{
        This chapter is more of practical interest. 
        It is important that \AVA is used in a proper way because only
        in that case the user can get maximum from it.
      }
  \end{enumerate}



%%%%%%%%%%%%%%%%%%%%%%%%%%%
% INSTALLATION  
  
\chapter{Installation}

  \AVA is distributed as a source code and should compile on most
  of the UN*X systems. Hardware and software requirements for compilation 
  and installation procedure are:
  \begin{itemize}
    \item GNU C++ compiler version 2.7.2.1 or higher.
    \item 3 MB of hard disk space
    \item 8 MB of memory with swap is suggested \\
          \remark{
          It also compiles on 4 MB systems in about one hour and more
          }
  \end{itemize}  
  Till now \AVA was tested and used on Debian and Redhat Distributions.


\section{Obtaining the \AVA}

  \AVA can be downloaded from primary web site:  
  \wwwlink{http://medo.fov.uni-mb.si/mapp}
  Mirror sites are not available yet.
  
  If you do not have former versions of \AVA you have to download
  complete .tar.gz package and not just \emph{diff} files.
  After you download the latest release extract it as:
  \astep{tar -zxf ava-x.y.z.tar.gz}
  Enter the \aistep{ava-x.y.z} directory and you shall see
  the following directory structure, where:
  \begin{center}
  \begin{tabular}{ll}
    \sdir{.} & info files \\
    \sdir{avalib} & \AVA library \\
    \sdir{src} & assembler source code \\
    \sdir{doc} & document source \\ 
    \sdir{examples} & assembler examples \\
  \end{tabular}
  \end{center}
  
  
\section{Configuring}

  By the default \AVA library is copied to the
  \astep{/usr/local/uTools/ava}
  directory and \sdir{ava} executable to the
  \astep{/usr/local/bin}
  directory. If you disagree with the defaults, please edit the:
  \astep{ava-x.y.z/src/Makefile}
  and change directories to your requirements.
  This settings affects both, compilation and installation procedure.

  Postscript and HTML version of the document is copied to the
  \astep{/usr/doc/uTools/ava}
  You can change the default settings in the:
  \astep{ava-x.y.z/doc/Makefile}
  
  
\section{Compiling}

  Since \AVA is a console application there are actually no
  parameters to be set by users individually. Simply enter
  the directory \aistep{ava-x.y.z/src} and type:
  \astep{make}
  \note{\AVA should compile without errors and warnings. 
        If any warning is present regarding to the \AVA source
        please report bug as described in Bug Report section 
        \ref{sec-bugreport}}
        
                
\section{Installation}
  
  To install software change directory to \aistep{ava-x.y.z/src} and
  type:
  \astep{make install}
  After installation you may enter the \aistep{ava-x.y.z/examples}
  directory and type:
  \astep{ava endian.s}
  to compile and:
  \astep{ava endian.o}
  to link it. If this example did not work, compilation or installation
  procedure has failed.
  By the default the executable code is put into
  \sdir{a.out} file unless specified otherwise.
  
  To install documentation in Postscript and HTML formats,
  change directory to \aistep{ava-x.y.z/doc} and
  type:
  \astep{make install}



%%%%%%%%%%%%%%%%%%%%%%%%%%%
% COMMAND LINE OPTIONS

\chapter{Running the \AVA}

  \AVA is a console application running in batch mode. It reads input
  either from a file or from the standard input (stdin). 
  Output is written to another file or to the Standard Output (stdout). 
  By default error messages are printed to the Standard Error (stderr).
    
  \section{I/O Streams}
  
  Assembler and linker are integrated. Which of them is invoked is 
  identified from the source filename extension. 
  If Standard Input (stdin) and/or Standard Output (stdout) are
  specified \AVA automatically invokes Assembler. Linker cannot use
  these two streams as input/output streams.
  
  The following suffixes of source file names indicate kind of
  processing to be done:
  \begin{center}
  \begin{tabular}{l|l}
    \hline
    {\bf suffix} & {\bf input/output, type, action} \\
    \hline
    \sdir{.s} & i, assembler source, assemble \\
    \sdir{.o} & i/o, object, link \\
    \sdir{.inc, .h} & input, include \\
                    & \emph{not usually named on command line} \\            
    \sdir{.lst} & o, listing report \\ 
    \sdir{a.out} & o, linker default output \\
  \end{tabular}
  \end{center}  
  Assembler can assemble one file at a time only. 
  
  
  \section{Command Line Options}
  
  General syntax of the \AVA command line parameters:
  \astep{ava -option$1$ ... -option$n$  
         \ \ file$1$.x ... file$n$.x}
  One option can be specified after '-' character only. 
  Full path name should be named for all files that are not found in the
  current directory.
  
  \note{The order of options does not matter but the order of files is
        very important.}
  Files are linked in exactly the same sequence as listed in the command line.
  This has strong effect on virtual symbols. Please refer to section 
  \ref{sec-macro} for details.
  
  Several options are available to:
  \begin{itemize}
    \item get on-line help,
    \item set the assembler and linker behaviours and
    \item to control reports.

  \end{itemize}
  
  \subsection{Help}
  
    \AVA options described in the following two sections are also
    documented on-line, using the -h switch. For example type:    
    \astep{ava -h}

  
  \subsection{Assembler and Linker Options}
  
  \begin{center}
  \begin{tabular}{|l|l|}
    \hline
    {\bf option} & {\bf description} \\
    \hline \hline
    \sdir{-o} \emph{outfile} & Redirects output to the \emph{outfile}. \\
              & Hint: if \emph{outfile} equals \emph{stdout}, standard output \\
              & is used. \\
              & \emph{example:} \aistep{ava -o project main.o print.o} \\
    \hline
    \sdir{-p} & Use stdin as input and stdout as output \\ 
              & unless -o is specified. \\
              & \emph{example:} \aistep{ava -p <file.s | gzip >file.o.gz} \\
    \hline    
    \sdir{-A}\emph{device\}} & Defines target device \emph{device}. \\
    \hline    
    \sdir{-D}\emph{macro\{=val\}} & Defines macro with value \emph{val}. \\
              & If \emph{val} is not specified 1 is assumed. \\
              & \emph{example1:} \aistep{ava -DVER=2 main.s} \\
              & \emph{example2:} 
                \aistep{ava -DSTR="$\backslash$"string$\backslash$"" main.s} \\
    \hline    
    \sdir{-f}\emph{macro\{=val\}} & Defines public macro with value \emph{val}. \\
              & To macro two underlines are inserted at the begining. \\
              & If \emph{val} is not specified 1 is assumed. \\
              & \emph{example1:} \aistep{ava -favr\_noskipbug main.s} \\
    \hline
    \sdir{-I}\emph{directory} & Add include directory to the search list. \\
              & \emph{example:} \aistep{ava -I../include main.s} \\
    \hline
    \sdir{-I}\emph{filename} & Include \emph{filename} to the source. \\
              & \emph{example:} \aistep{ava -I../include main.s} \\
    \hline    
    \sdir{-T}\emph{\{filename\}}
              & Include \emph{filename} to the source. \\
              & if \emph{filename} is not given \emph{target.inc} is used. \\
              & Thid file is the first file in the queue - before those\\
              & specified by the -I\emph{filename} option. \\
              & It is searched in the default directory\\
              & and then on the predefined list. See section 
                  \ref{sec-preproc} \\
              & for details. \\
    \hline
  \end{tabular}
  \end{center}  
  
  
  \subsection{Reports Options}
  
  \begin{center}
  \begin{tabular}{|l|l|}
    \hline
    {\bf option} & {\bf description} \\
    \hline \hline
    \sdir{-v} & Turn on info messages.\\ 
	      & (Assembler and Linker status, Segment Tree, ...) \\    
              & \emph{example:} \aistep{ava -v main.s} \\
    \hline
    \sdir{-L} & Turn on listing reports for file being \\ 
              & assembled. \\
              & \emph{example:} \aistep{ava -T main.s} \\
    \hline
    \sdir{-l}\emph{logfile} & Redirect segment tree information \\ 
              & and status reports to the file. Errors and warn- \\
              & ings are printed to both, stderr and \emph{logfile}. \\
              & \emph{example:} \aistep{ava -lava.log main.s} \\
    \hline
  \end{tabular}
  \end{center}
  
  Options that take special effect on assembler source are further
  explained in the next chapter.



%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ASSEMBLER LANGUAGE

\chapter{Assembler Language}
\label{sec-asm}

\section{Input}

  Assembler source consists of elements called tokens. 
  The token may be one of the following: numbers, string, quoted string,
  preprocessor directives, math and control symbols and remarks.
  To each type of token a range of valid characters is declared. 
  If token does not match that range lexer produces an error and assembler
  terminates.

  The types of tokens and ranges are represented in the table below. 
  \begin{center}
    \begin{tabular}{r|l}
      \hline
      {\bf token} & {\bf input characters} \\
      \hline
      decimal number & \{0..9\} \\
      hex number & \$\{0..9,a..f,A..F\}, 0x\{0..9,a..f,A..F\} \\
      string & \{a..z,A..Z,\_\}\{a..z,A..Z,0..9,\_\},... \\
      quoted string & ``...'' \\
      preprocessor & $\sharp$\emph{string} \\
      math symbols & \{+,-,*,/\,=,$<,>,\&,|,\wedge$\} \\
      control symbols & \{., , ,\{,\},(,),$\backslash$ \} \\
      standard C remarks & /* ... */ \\
      standard asm remarks & ; ... \\
    \end{tabular}
  \end{center}  

  \subsection{Expressions}
  
    Expressions are made of numbers, strings, math and control
    symbols. \AVA expression solver understands the following
    operations:    
    \begin{center}
      \begin{tabular}{r|l}
        \hline
        {\bf symbol} & {\bf operation} \\
        \hline
        $+,-$ & add, subtract \\
        $\&,|,\wedge,<<,>>$ & and, or, xor, logical shift left, right \\
        $*, /$ & multiply, divide \\
        $<,>,==,<=,>=$ & less, greater, equal, less/greater or equal \\
      \end{tabular}
    \end{center}          
    The general form of expression:
    \astep{((A \emph{operation} B) \{\emph{operation} C\})}
    where \aistep{A,B} and \aistep{C} may be expressions also.


\section{Preprocessor}
\label{sec-preproc}


  \subsection{Directives}

    \AVA provides C like preprocessor. Preprocessor directive starts with
    $\sharp$ character followed by a command. The table below lists the
    supported directives:
    
    \begin{center}
      \begin{tabular}{|l|l|}
        \hline
        {\bf directive} & {\bf meaning} \\
        \hline \hline
        
        $\sharp$arch \emph{target\_device} & Defines target device. \\
        \hline                

        $\sharp$include "\emph{filename}" 
          & Includes \emph{filename} to the current source.\\
        \hline
        
        $\sharp$adddir "\emph{filename}" 
          & Adds alternate include directory to the list. \\          
        \hline
                
        $\sharp$define ... 
          & Defines macro. \\
        \hline

        $\sharp$undefine \emph{macro\_nm}
          & Undefines macro \emph{macro\_nm}. \\
        \hline
        
        $\sharp$ifdef \emph{macro\_name}
          & If macro \emph{macro\_name} is defined, enter.\\
        \hline
        
        $\sharp$if \emph{expression}
          & If \emph{expression} is true, enter.\\
        \hline        
          
        $\sharp$else
          & \aistep{$\sharp$ifdef \emph{macro\_name} ... $\sharp$else ... 
              $\sharp$endif}. \\
        \hline
                        
        $\sharp$error \emph{message}
          & Generates error and report message. \\
        \hline          

        $\sharp$print \emph{message}
          & Prints info message. \\
        \hline
                
      \end{tabular}
    \end{center}
    
    
    \subsubsection{Directive $\sharp$arch \emph{target\_device}}
        
      Defines target device.
      This directive defines macro \emph{target\_device} and
      includes the file \emph{../uTools/ava/arch.inc}.
      File \emph{arch.inc} declares memory model, actual device,
      memory mapped I/Os, ...etc. See content of the
      \emph{arch.inc} for details.
      \begin{example}
      \begin{verbatim}
      
      /* set device */
      #arch AT90S1200
      \end{verbatim}
      \end{example}
      Target device can be also declared by the -A switch.      
        
        
    \subsubsection{Directive $\sharp$include "\emph{filename}"}
    
      Includes \emph{filename} to the current source.
      The file specified is first searched in the current
      directory and if it is not found, \AVA continues
      searching in the alternative directories as specified
      by the -I\emph{directory} option on the command line
      or by the $\sharp$adddir "\emph{filename}" 
      directive in the source code.
     \begin{example}
      \begin{verbatim}
      
      /* define model */
      #arch AT90S1200
      
      /* 
         Include standard bit definitions according to the
         selected device. 
      */
      #include "avr.inc"
      \end{verbatim}
      \end{example}      
       
            
    \subsubsection{Directive $\sharp$adddir "\emph{filename}"}
      Adds alternate include directory to the search list
      used by the $\sharp$include directive. This directive
      is mostly used by the Target Definition File.      
      \begin{example}
      \begin{verbatim}
      
      /* target.inc */
      
      /* Set additional include directories ... */
      #adddir "../csys/include/asm"
      #adddir "../common/include/"
      \end{verbatim}
      \end{example}      
      
                
    \subsubsection{Directive $\sharp$define \emph{macro\_nm}}
      Defines macro with name \emph{macro\_nm}. 
      Since macros are a little bit extended
      they are explained in the separate section \ref{sec-macro}.
      See example \ref{ex-ifb1} and \ref{ex-ifb2}.

    \subsubsection{Directive $\sharp$undefine \emph{macro\_nm}}
      Undefines macro \emph{macro\_nm}.      
      See example \ref{ex-ifb1} and \ref{ex-ifb2}.
        
    \subsubsection{Directive $\sharp$ifdef \emph{macro\_name}}  
      Enters the $\sharp$ifdef ... $\sharp$endif block if macro
      \emph{macro\_name} is defined.
      \begin{example}
      \label{ex-ifb1}
      \begin{verbatim}
      
      #ifdef __NICE_LEVEL
      #  define __NICE_LEVEL	49
      #endif
      \end{verbatim}
      \end{example}
      
    \subsubsection{Directive $\sharp$if \emph{expression}}
       Similar to $\sharp$ifdef except that expression may
       be given. All undefined macros within the 
       expression are treated as zeros.
      \begin{example}
      \label{ex-ifb2}
      \begin{verbatim}
            
      #if (__NICE_LEVEL < 41)| (__NICE_LEVEL > 58)
      #  undefine __NICE_LEVEL
      #  define __NICE_LEVEL	49
      #endif
      \end{verbatim}
      \end{example}
      
          
    \subsubsection{Directive $\sharp$else}
       Else can be used in conjunction with $\sharp$ifdef directive.
       General form is:
       \aistep{$\sharp$ifdef \emph{macro\_name} ... $\sharp$else ... 
         $\sharp$endif}.         
      \begin{example}
      \begin{verbatim}
      
      #ifdef __NICE_LEVEL
      #  define __NICE_LEVEL	49
      #else
      #  undefine __NICE_LEVEL
      #  define __NICE_LEVEL	49
      #endif
      \end{verbatim}
      \end{example}
         
                                 
    \subsubsection{Directive $\sharp$error \emph{message}}
       Generates error and report message.
      \begin{example}
      \begin{verbatim}
      
      /* 
         Use of parethness is recommended because of the macro
         replacements. 
      */  
      #ifndef __NICE_LEVEL
      #  error "__NICE_LEVEL is not defined!"
      #endif
      \end{verbatim}
      \end{example}
       

    \subsubsection{Directive $\sharp$print \emph{message}}
       Prints info message. Message is terminated by a
       new a line.
      \begin{example}
      \begin{verbatim}
      
      /* Prints __NICE_LEVEL to the stdout and log file */
      #print "__NICE_LEVEL = " __NICE_LEVEL
      \end{verbatim}
      \end{example}
       


  \subsection{Architecture Definition File}
  
    The Architecture Definition File (\emph{arch.inc}) is a part of the 
    \AVA library. This file includes all the information of the 
    supported models and families. 
    
    The file \emph{arch.inc} is automatically included after the
    $\sharp$arch preprocessor directive.
    \note{Never include or modify \emph{arch.inc} file
          unless all consequences are known.}
  

  \subsection{Target Definition File}

    \AVA is a segment oriented assembler. Each piece of code may be
    placed in any kind of segment. Such a mechanism provides maximum control 
    over the code and prevents from undesired errors
    (see section \ref{sec-segment} for detailed explanation on segments).
    
    One of the mechanism that helps to keep things in order is 
    the Target Definition File or \emph{target.inc}. For larger
    micro-controller systems with memory mapped I/Os, "huge" software,
    the \emph{target.inc} file should provide complete hardware
    description. Using the -T option in the command the \emph{target.inc} 
    file will be included to each source automatically. 
    
    Of course, adding the line \aistep{$\sharp$include "target.inc"} 
    to each source has the same effect but -T option
    might be used as a shortcut.
    
    One of the most important things that the linker should be instructed
    is about memory holes. If linker is not notified about them, it cannot 
    avoid these holes and data segment {\bf may be} improperly placed!
    Please see examples in the chapter \ref{sec-design} and section
    \ref{sec-segment} for help on declaring the memory holes.


\section{Symbols}
\label{sec-symbol}
  
  There are two kind of symbols:
  \begin{itemize}
    \item Macros and
    \item Labels
  \end{itemize}
  To label offset is assigned and macro can be used to
  replace expressions and/or assembler code.
  
  \subsection{Attributes}
  
    The present section describe general properties of the macros
    and labels. Attributes declare the different behaviours of the
    symbols during compilation and linkage process. The attributes
    are:
    \begin{center}
      \begin{tabular}{|r|l|}
        \hline
        {\bf attribute} & {\bf meaning} \\
        \hline \hline
        
        internal & Declares internal symbol.\\
          & This symbol is declared within current object file \\
          & only and is completely invisible from the outside. \\
          & \emph{This is the assembler default attribute.} \\
        \hline
        
        public & Create public symbol. \\
          & Public symbol is visible inside and outside \\
          & of the current object. \\
        \hline
        
        extern & Creates reference to other objects. \\
          & Public symbols defined in other objects are visible \\
          & to current object if and only if references exist. \\
        \hline
        
        virtual & Creates virtual symbol. \\
          & This special flag allows further redefinition of the symbol. \\
          & The value and attribute of the symbol can be redefined by \\
          & another definition of the same symbol. \\          
        \hline
        
      \end{tabular}
    \end{center}
    
    Symbol can have assigned multiple properties. But not all of
    them are valid. For example; symbol declared as (public, virtual) is
    invalid but (extern, virtual) is right. Note that attribute (extern)
    creates references outside the current object and (public) only
    exports the symbol. Virtual symbol can be only replaced by outside
    symbol if reference exist.
    
    The following combinations make sense:
    \begin{center}
      \begin{tabular}{|r|l|}
        \hline
        {\bf attribute} & {\bf meaning} \\
        \hline \hline
       
        none & Creates internal symbol. \\
        \hline
        
        public & Creates public symbol. \\
        \hline
        
        extern & Creates reference to other objects. \\
        \hline        
        
        virtual & Creates internal virtual symbol. \\
          & \emph{This declaration makes sense for development} \\
          & \emph{purposes only.} \\
        \hline        

        virtual extern & Creates global virtual symbol. \\
        \hline

      \end{tabular}
    \end{center}          


  \subsection{Label}
  
    To label offset is assigned.
    General form of declaration:
    \astep{attributes label\_name\{:\}}
    The semicolon ':' is required only if there is no attribute assigned
    to the label.    
    
  \subsection{Macro}
  \label{sec-macro}
  
    Macro replaces numbers with constants, expressions or even
    larger parts of code.
    General form of declaration:
    \astep{$\sharp$define attributes macro\_name($a_0$,$a_1$,...,$a_n$) 
           macro\_string}
    If \emph{macro\_string} does not fit into one line, use the
    $\backslash$ character on the end of each non-last line.
    Also the parameters $a_0, a_1, ...$ and on may be split into two or 
    more lines. Additional character on the end of the line is not needed 
    since every parameter is terminated either by coma or ) character.
    
    The general form can be written as:
    \astep{$\sharp$define attributes macro\_name($a_0$,$a_1$,...,$a_n$) 
           macro\_string$_0$ $\backslash$ \\
           macro\_string$_1$ $\ \ \backslash$ \\
           ...\\
           macro\_string$_{n-1}$ $\backslash$ \\
           macro\_string$_n$
    }
    \note{ava-0.1.8 does not yet support sections and labels. 
          They should not be used within the macro.}



\section{Segments}
\label{sec-segment}

    The importance of the full control over the code is crucical and cannot
    be explained in one hour course. Specially if the target device
    has limited memory - okay, every machine on the planet is 
    limited, but 1 or 8 kb of memory is something heavily
    under the normal range people know it from the PCs.
    
    Treatment of segments is heavily extended in comparison to the 
    other assemblers and linkers. The standard command
    \astep{org offset}
    does not exist. Better result is achieved by using the higher
    order segments.

    The \AVA segments form multi-children tree structure just as like
    a file system. The \emph{root} of the segments represents target
    its children define physical memory areas. Moreover this areas
    can be even expanded to abstract areas but let us describe them
    later on. 
    
    Simple representation of the program for the \AVR micro-controller
    is shown in figure \ref{fig-segments}.
    \fig{pic/segments.eps}
        {An example of a segment structure.}
        {fig-segments}
    Here the \emph{flash, eeprom} and \emph{eram} are \AVR base segments.
    They declare physical memory models and the downloading tool
    is expecting this segments. 
    
    From some reasons it makes sense to define the segment order:
    \begin{quote}
      \emph{The segment order $S_O$ of the segment $S$ is the number of 
            vertices on the shortest path from the segment $S$ to the 
            {\bf root}. The vertex of the segment $S$ is also included.}
    \end{quote}
    Now we can say: base segments are segments of the first order. 
    
    \subsection{Attributes}
    
      The following segments attributes are available. Each attribute
      is described in greater details in further sections.
      \begin{center}
        \begin{tabular}{|r|l|}
          \hline
          {\bf attribute} & {\bf meaning} \\
          \hline \hline

          abstract & Declare abstract segment that \\
            & never appears in the output.\\
          \hline          
          removable & Allow linker to remove that segment\\ 
            & if it is not used.\\
          \hline                  
          abs=\emph{val} & Absolute origin of the segment. \\
          \hline          
          size=\emph{val} & Fixed size of the segment. \\
          \hline          
          mirror=\emph{segment} & Declares mirror segment. \\
          \hline
          align=\emph{val} & Keep segment aligned to \emph{val} bytes. \\
          \hline
          
        \end{tabular}
      \end{center}
      Multiple attributes can be assigned to single segment.

      \subsubsection{Abstract Segment}
      
        If we take a look at our previous example in figure 
        \ref{fig-segments} we see segment named \aistep{eram}.
        In any case, these segment has nothing to do in the output
        for the \AVR micro-controller since downloading tool cannot
        load data to the volatile memory.
        
        Every segment that is used for internal processing only
        is called \emph{abstract} segment. This segment exist as
        such until the linker is finished.
        
        The mechanism of abstract segment can be generalised and
        can be used for any kind of processing. For example: magic
        tables. The user can specify new segment to which every 
        device driver defines a byte with a corresponding label.
        After linkage process to every byte an unique address is assigned
        and thus unique magic number in the corresponding label.
      
      \subsubsection{Removable Segment}
      
        The \emph{removable} attribute efficiently extends object 
        files to libraries. Each function should be given be placed
        in its own higher order removable segment which consist at
        least {\bf ONE} public label and {\bf not} macro.
        If this public label was used at least once by other source
        the segment will be linked together with the rest of the code.
        Otherwise it is removed.
      
      \subsubsection{Absolute Origin}
      
        This attribute sets the final position of the segment and
        it must be specified to all first order segments.
        The segments which are not absolutelly positioned are called
        floating segments and are placed by \AVA linker. The complete
        segmentation report is printed to the log file or to the
        standard output if log file is not given.
      
      \subsubsection{Fixed Size}
      
        If the size of segment is not given the length may vary according 
        to the usage. These segments are called variable segments.
        Because the root segment does not know the lengths of the first order
        segments their maximum size must be defined.
        \note{Every higher order segment (children) becomes variable
              segment if its size is not specified.}
      
      \subsubsection{Mirror Segment}
      
        Let us go back to the example again where we already said
        few words about the \aistep{eram} segment. Now imagine the
        second case
        \begin{quote}
        We declare some data within the \aistep{eram} segment and
        would like to get it there, anyhow, after the \AVR wakes up.
        \end{quote}
        This typical example shows how does the C compiler work.
        The GNU C compiler stores data in second order segment named
        \aistep{gcc\_data\_section}. Linker copies this data to flash
        memory during the linkage process and checks for boundaries.
        The new segment in the flash memory is called \emph{mirror} segment.
        The mirror segment must be declared before it is referenced.
        
      \subsubsection{Align Option}
      
        Sets alignment factor of the segment length.
        It can effect variable size segments only.
        The default segment alignment is set to 1 byte.


    \subsection{General Declaration Form}
    
      Before we introduce the general form of the segment declaration
      line the general form of the segment name must be defined.
      Going back to our example we define:
      \begin{itemize}
        \item each path is represented by a dot and
        \item vertex by its name
      \end{itemize}
      Since \aistep{root} segment and the first path are always
      present it makes sense we skip it. We get:
      \astep{segname = $S_1$.$S_2$.$S_3$...}    
      And the general form of the segment:
      \astep{seg attributes segname}
      
      The same form initializes or sets the segment. See examples
      in chapter \ref{sec-design}.
      
      \begin{example}
      \begin{verbatim}
    
      /* 
         Create and set the second order floating and variable 
           segment to the eram segment named: data 
      */
              seg eram.data
              
      /* 
         Map I/O memory ports to the eram segment of the AVR MCU.
      */
              seg abs=0 size=0x20 eram.registers
      
      \end{verbatim}
      \end{example}      
      
            

\section{Keywords}

  The present section represents additional keywords for controlling
  the data storage and special keywords used by Architecture Definition
  File.

  \subsection{Define Storage}

    General declaration form:
    \astep{ds.$x$ $n$}
    Reserves space in a segment with length $n$ times the size of 
    the data type $x$.
    \begin{example}
    \begin{verbatim}
    
    /* reserve 32 bytes of space in eram.data segment */
            seg     eram.data
    buf:    ds.b    0x20
        
    /* and 20 words for table */
    tbl:    ds.w    20      
    \end{verbatim}
    \end{example}      
    

  \subsection{Define Constant}

    General declaration form:
    \astep{dc.$x$ \{number,string\},\{number,string\},...}
    Initializes constants in a segment of data type $x$.
    \begin{example}
    \begin{verbatim}
    
    /* New Line Chatacter */
    #define NL      10
    
    /* Hello Message (split in several lines) */
            seg     flash.data            
    hello:  dc.b    "Hello LED!",NL,
                    "Hello again.",NL,
                    0        
                    
    /* store address of the label for indirect call */
    /* Note: PC counts words and not bytes (LSB must be removed) */
    putc_f: dc.W    _fputc >> 1		
    \end{verbatim}
    \end{example}      
    
    
  \subsection{Data Types}
  
    \AVA understands the following data types:
    \begin{center}
      \begin{tabular}{|c|l|}
        \hline
        {\bf data type} & {\bf meaning} \\
        \hline \hline
        b & byte \\
        w & little endian word \\
        W & big endian word \\
        l & little endian long \\
        L & big endian long \\
        \hline
      \end{tabular}
    \end{center}
    Little endian constants are stored in the form
    \astep{$B_{LSB}B_{1}...B_{n-1}B_{MSB}$}
    and big endian as:
    \astep{$B_{MSB}B_{n-1}...B_{1}B_{LSB}$}
    where MSB is the most significant byte and LSB the less significant
    byte.


  \subsection{Device}
  
    General declaration form:
    \astep{device \AVA\_Arch\_Modul parameters ...}
    This keyword is used by the Architecture Definition File only.


\section{Instruction Set}

  Please refer to the micro-controllers data book for complete list
  and explanation.



%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PROGRAMMING DESIGN

\chapter{Programming in \AVA}
\label{sec-design}

  This chapter introduces simple examples and solutions some
  common problems. Examples are included in the \aistep{examples} 
  directory.
  
\section{Hello World!}
  
  The first typical example usually introduced by C and other languages
  is "Hello World!". Starting on a new micro-controller this "Hello World!"
  example is not that small piece of code. Driver for the UART/RS-232
  module needs to be written, simple data structure as FIFO and
  printf function is required. All together counts about few hundreds 
  bytes of code what is far too much for the first assembler program.
    
  Let us better try to turn on and off a light emitting diode (LED) using
  the AT90S1200 \AVR chip. Before going on please read chapter \ref{sec-asm}
  which describes Assembler Language in details and section \ref{sec-avr}
  for \AVR dedicated features.
  
  \subsection{Declarations}
  
    There is one declaration that must be written in every source before
    first line of code appears.
    This is the target selection. Example:
    \begin{verbatim}
    #arch AT90S1200
    \end{verbatim}
    According to the \AVR family (section \ref{sec-avr}) we see that
    by default \aistep{flash} memory segment is selected. Thus every line
    after the $\sharp$arch ... directive will appear in the flash memory.
    
    It is more safe to put each type of code into
    a separate segment of higher order which name reflects the purpose
    of that segment. Thus program could be put in the segment 
    \aistep{flash.code}.
    
    And that is all.
    

  \subsection{Hello LED!}

    The following code turns on the led on port PB0 by setting the
    PB0 pin low.
    \begin{verbatim}
    /* examples/helloled.s */

    /* set target device; see arch.inc for other models. */
    #arch AT90S1200

    /* Load include file of predefined port definitions.
       This file should not be included until device is selected. 
       See inside of the avr.inc for details.
    */
    #include "avr.inc"

    /* general declarations */
    #define LED1        PB0
    
    /* calculate port B direction */
    #define PORTB_DIR   BV(LED1)

    /* register naming */
    #define Tmp	        r16

    /* AVR AT90S1200 vectors start at address 0 */
        seg abs=0 flash.code
        
        rjmp __reset_   /* this vector is executed on every reset */
        reti
        reti
        reti
    
    /* Initialize hardware ports */    
    __reset_:
        ldi Tmp, PORTB_DIR  /* set port B direction */
        out DDRB, Tmp
        
        clr Tmp             /* clear outputs and disable pull-ups */
        out PORTB, Tmp
        
    loop: 
        rjmp loop           /* loop for ever */

    \end{verbatim}
  
    Even though this example turn on the LED only it includes all
    the properties of a larger software written in assembler.
    When you write in assembler take special care on:
    \begin{itemize}
      \item write remarks everywhere the code does not reflect
            the meaning visible from 100 meters.
           
      \item use macros to replace any kind of number (constant)
      \item use macros to keep your code independed of the hardware
            configuration - as LED1 in above example
            
      \item use segments more extensively - if there is table present
            in the flash memory do not put it in the \aistep{flash.code} 
            segment but \aistep{flash.sin\_table} for example.
            
      \item assign name to every register!
    \end{itemize}
    There are some rules which make assembler source even more clean.


\section{Using the Target Declaration File}

  To the \emph{target.inc} all hardware specifications should be given.
  The purpose of this file is to keep thousands lines of assembler code 
  split in several files so far organised.
  Files that use \emph{target.inc} can be compiled with -T option which
  automatically includes the \emph{target.inc}. Otherwise the preprocessor
  line:
  \astep{include "target.inc"}
  present in each source of the project does completely the same.
  The -T switch forces the Target Declaration File to be read first.
  Follow the files given by the -I switch and then the assembler
  source.
    
  An example is given in \aistep{examples} directory and prototype of
  the \emph{target.inc} file is located in \aistep{avalib} directory
  (or in \aistep{/usr/local/uTools/ava/target.inc}).
  
  \subsection{Target Declaration}
  
    The \emph{arch.inc} file specifies the default parameters of
    the memory segments of the \AVR family. If the target provides more
    memory the linker must be instructed. Otherwise it cannot be
    used.
    
    Several macros are provided within the \emph{arch.inc}. To change
    size of the RAM segment macro \aistep{\_\_ERAM\_SIZE} is provided
    as described in section \ref{sec-avr}.
    
    Even though \AVA linker requires that only one object has set its
    segment size to the maximum value it is better to put that common
    properties in common file - the \emph{target.inc}.
    
    Example of target declaration:
    \begin{verbatim}
    /* Declare Size of the eram segment 
      (before device declaration!) */
    #define __ERAM_SIZE     0x1002

    /* Declare MCU (AT90S8515 has enabled Wrap Around Option) */
    #arch AT90S8515
    \end{verbatim}
    
    
  \subsection{Memory Mapped Ports}
  
    The next {\bf very} important thing are memory mapped ports.
    \AVA linker cannot know where the target device has memory mapped
    ports if you do not declare them.
    
    Memory mapped ports are declared as higher order segments of fixed
    size and fixed absolute address. Example:
    \begin{verbatim}     
    /* Memory mapped IO ports of my test board */
    #define _IO_PORTS       0x1000

    /* Declare segments. Protect eram segment to clash with
       the following io registers. */
    seg abs=_IO_PORTS size=0x2 eram.ioports

    /* Register Names: */
    #define ADC_DATA        _IO_PORTS
    #define ADC_CONTROL     _IO_PORTS+1

    \end{verbatim}
    Besides segment declaration macros of the register names 
    should also be provided.
    


%%%%%%%%%%%%%%%%%%%%%%%%%%%
% APPENDICES
\appendix

\chapter{Supported Families}

  The following specifications are provided as advanced information only
  and they are already considered in the \aistep{arch.inc} file.
  

\section{\AVR Family Micro-Controllers}
\label{sec-avr}
  
  AVA supports full range of \AVR family micro-controllers.
  In general they can be all sorted in three groups.
  
  \begin{center}
  \begin{tabular}{|l||l|} 
  \hline
    {\bf Group} & {\bf Models} \\ 
    \hline \hline
    1 & AT90S1200 \\ \hline
      & AT90S2313, AT90S2323, AT90S2333, AT90S2343 \\
    2 & AT90S4414, AT90S4433, AT90S4434 \\
      & AT90S8515 AT90S8535 \\ \hline
    3 & ATmega603, ATmega103 \\ \hline
    4 & \emph{Not yet available.} \\ \hline
  \end{tabular}
  \end{center}  
  The \AVR device is selected by writing the:
  \begin{quote}
    \tt device AVR group\_number
  \end{quote}
  in the source code.
  
  \subsection{\AVR Groups}
  
  Besides memory models \AVR micro-controllers have different number
  of instructions. The following table represents the difference 
  between first/second, second/third and third/fourth groups.
  \begin{center}
  \begin{tabular}{|l||l|} 
  \hline
    {\bf Group} & {\bf Instructions} \\ 
    \hline \hline
    1/2 & adiw, icall, ijmp, ld/st *X*, ld/st *Y*, ld/st -Z+, \\
      & ldd/std, lds, lpm, pop, push \\
    \hline
    2/3 & call, jmp \\    
    \hline
    3/4 & mul \\
    \hline
  \end{tabular}
  \end{center}  
  
  \subsection{Memory Models}
  
  The following segments are provided within the arch.inc:
    \begin{center}
  \begin{tabular}{|l||l|l|} 
  \hline
    {\bf Group} & {\bf HW Segments} & {\bf Abstract Segments} \\ 
    \hline \hline
    1 & \seg{flash}, \seg{eeprom} & \\
    \hline
    2, 3 & \seg{flash}, \seg{eeprom} & \seg{eram}, \seg{eram.registers},
             \seg{eram.io\_space} \\
    \hline
  \end{tabular}
  \end{center}

  Segment sizes depend on a chosen model. 
  Segments \seg{eram.registers} and \seg{eram.io\_space} are of
  fixed size and have absolutely positioned segments. 
  
  The user should change the size of the RAM - \seg{eram} segment. 
  By the default, minimum values are used for all models - what includes
  internal SRAM only. Before declaring the device set
  \aistep{\_\_ERAM\_SIZE} as shown in the following example:
  \begin{verbatim}
  #define __ERAM_SIZE 0x8000
  #arch AT90S8515
  \end{verbatim}
  As suggested by the \AVA this kind of declarations should move
  to the target specific \sfile{target.inc} file.
  
  By default, segment \aistep{flash} is selected.
  
  
  \subsection{Special Flags}
  
  \note{Flags must be declared as public macros.}
  
  The following flags are supported by the \AVR family:
  \begin{description}
    \item[AVR\_WRAP\_AROUND] Relative addressing capabilities of the
        relative calls can handle only up to 4 kb of memory in negative
        and positive directions. With this option, the top and
        the bottom addresses are joined together as they were linear
        and thus virtually extends the addressing space of the relative
        calls.
        This option was provided for 8 kb flash models only and allows
        \aistep{rjmp} instruction to cover the entire program memory.
        
    \item[avr\_noskipbug] Some AVR-CORES are found to have bug
        when pushing the program return address on interrupt occurence.
        This happens if and only if interrupt vector is executed
        while one of the skip instructions (sbrs,sbrc,sbis,sbic and cpse) 
        is being executed in its first or second cycle and if the instruction
        followed by the this instruction is the two-word (32 bit) 
        instruction such as lds,sts,jmp and call. Moreover, this bug
        occurs if and only if address of the two-word instruction points 
        beyond 0x400.
        
        The \AVA assembler performs check and reports warning if such
        a bug might happen. Since later revisions of the AVR MCUs
        have fixed that bug you might need to append the option
        \astep{-favr\_noskipbug}
        to the command line in order to disable the \AVA bug hunting 
        mechanism.
  \end{description}
  


%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUPPORT

\chapter{Support}
\label{sec-support}

\section{New Releases}

  New releases, updates and other information can be found
  at \AVA primary site:
  \astep{http://medo.fov.uni-mb.si/mapp}
  You can also subscribe to the MAPP \AVR Mailing List
  \astep{avr@medo.fov.uni-mb.si}
  To subscribe, send message to:
  \astep{majordomo@medo.fov.uni-mb.si} 
  with the following text in the body of the message:
  \astep{subscribe avr \emph{your\_email\_address}}
  Additional questions can be sent to my E-mail address:
  \astep{uros.platise@ijs.si}

\section{Bug Report}
\label{sec-bugreport}

  Before reporting a bug please try to locate which
  part of the input code crashes down either assembler
  or linker.
  Send a detailed report to \AVR Mailing List:
  \astep{avr@medo.fov.uni-mb.si}
  or to my E-mail address:
  \astep{uros.platise@ijs.si} 



%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CONTACT ADDRESSES

\chapter{Contact Addresses}

  \begin{verbatim}
  Uros Platise
  Seljakovo naselje 45
  SI-4000 Kranj
  Slovenia

  telephone: +386 64 312 457
  E-mail: uros.platise@ijs.si
  \end{verbatim}

\end{document}
